#!/bin/bash
DIR=$(dirname $0)
PWDPATH=$(cd $DIR && pwd)

if command -v pnpm >/dev/null 2>&1; then
  echo "pnpm is installed"
else
  echo "pnpm is not installed!!!"
  exit
fi

cd $PWDPATH
clearDirList=("$PWDPATH" "$PWDPATH/app" "$PWDPATH/x-yaf" "$PWDPATH/x-libs")

install() {
  echo "*****开始安装依赖包*****"
  pnpm install

  cd $PWDPATH/app
  pnpm install

  echo "*****安装依赖包完成*****"
}

clean() {
  echo "*****开始删除node_modules目录*****"
  # shellcheck disable=SC2068
  for dirPath in ${clearDirList[@]}; do
    if [ -d "$dirPath/node_modules" ]; then
      echo "$dirPath/node_modules"
      rm -rf $dirPath/node_modules
    fi

    if [ -f "$dirPath/pnpm-lock.yaml" ]; then
      echo "$dirPath/pnpm-lock.yaml"
      rm -rf $dirPath/pnpm-lock.yaml
    fi

    if [ -f "$dirPath/package-lock.json" ]; then
      echo "$dirPath/package-lock.json"
      rm -rf $dirPath/package-lock.json
    fi

    # 清除子嵌套目录
    if [[ "$dirPath" == "$PWDPATH/x-yaf" || "$dirPath" == "$PWDPATH/x-libs" ]]; then
      for childDirPath in $dirPath/*; do
        if [ -d "$childDirPath/node_modules" ]; then
          echo "$childDirPath/node_modules"
          rm -rf $childDirPath/node_modules
        fi

        if [ -f "$childDirPath/pnpm-lock.yaml" ]; then
          echo "$childDirPath/pnpm-lock.yaml"
          rm -rf $childDirPath/pnpm-lock.yaml
        fi

        if [ -f "$childDirPath/package-lock.json" ]; then
          echo "$childDirPath/package-lock.json"
          rm -rf $childDirPath/package-lock.json
        fi

        if [ -f "$childDirPath/tsconfig.tsbuildinfo" ]; then
          echo "$childDirPath/tsconfig.tsbuildinfo"
          rm -rf $childDirPath/tsconfig.tsbuildinfo
        fi

        if [ -d "$childDirPath/dist" ]; then
          echo "$childDirPath/dist"
          rm -rf $childDirPath/dist
        fi
      done
    fi
  done

  # 清理pnpm的缓存
  pnpm store prune

  echo "*****清理node_modules完成!*****"
}

case "$1" in
install)
  $1
  exit 0
  ;;
clean)
  $1
  exit 0
  ;;
*)
  echo $DIR
  echo 'Usage: {install|clean}'
  ;;
esac
